0%

Kubernetes集群中Pod间文件拷贝

如何在Pod间拷贝文件?

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*
copy file to pod
*/
package cp

import (
"archive/tar"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"strings"

corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
)

type Pod struct {
Name string
Namespace string
ContainerName string
}

func (i *Pod) CopyToPod(ctx context.Context, client *kubernetes.Clientset, config *rest.Config, srcPath string, destPath string) error {
reader, writer := io.Pipe()

if destPath != "/" && strings.HasSuffix(string(destPath[len(destPath)-1]), "/") {
destPath = destPath[:len(destPath)-1]
}

if err := checkDestinationIsDir(ctx, client, config, i, destPath); err == nil {
destPath = destPath + "/" + path.Base(srcPath)
}

go func() {
defer writer.Close()
err := makeTar(srcPath, destPath, writer)
if err != nil {
fmt.Println(err)
}
}()

var cmdArr []string

cmdArr = []string{"tar", "-xf", "-"}
destDir := path.Dir(destPath)
if len(destDir) > 0 {
cmdArr = append(cmdArr, "-C", destDir)
}
//remote shell.
req := client.CoreV1().RESTClient().
Post().
Namespace(i.Namespace).
Resource("pods").
Name(i.Name).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: i.ContainerName,
Command: cmdArr,
Stdin: true,
Stdout: true,
Stderr: true,
TTY: false,
}, scheme.ParameterCodec)

exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
if err != nil {
return err
}

err = exec.Stream(remotecommand.StreamOptions{
Stdin: reader,
Stdout: os.Stdout,
Stderr: os.Stderr,
Tty: false,
})
if err != nil {
return err
}
return nil
}

func checkDestinationIsDir(ctx context.Context, client *kubernetes.Clientset, config *rest.Config, i *Pod, destPath string) error {
return i.Exec(ctx, client, config, []string{"test", "-d", destPath})
}

func makeTar(srcPath, destPath string, writer io.Writer) error {
// TODO: use compression here?
tarWriter := tar.NewWriter(writer)
defer tarWriter.Close()

srcPath = path.Clean(srcPath)
destPath = path.Clean(destPath)
return recursiveTar(path.Dir(srcPath), path.Base(srcPath), path.Dir(destPath), path.Base(destPath), tarWriter)
}

func recursiveTar(srcBase, srcFile, destBase, destFile string, tarWriter *tar.Writer) error {

// defer func() {
// fmt.Println("d")
// if err := recover(); err != nil {
// fmt.Println(err) // 这里的err其实就是panic传入的内容
// }
// fmt.Println("e")
// }()

filepath := path.Join(srcBase, srcFile)
stat, err := os.Lstat(filepath)
if err != nil {
return err
}
if stat.IsDir() {
files, err := ioutil.ReadDir(filepath)
if err != nil {
return err
}
if len(files) == 0 {
//case empty directory
hdr, _ := tar.FileInfoHeader(stat, filepath)
hdr.Name = destFile
if err := tarWriter.WriteHeader(hdr); err != nil {
return err
}
}
for _, f := range files {
if err := recursiveTar(srcBase, path.Join(srcFile, f.Name()), destBase, path.Join(destFile, f.Name()), tarWriter); err != nil {
return err
}
}
return nil
} else if stat.Mode()&os.ModeSymlink != 0 {
//case soft link
hdr, _ := tar.FileInfoHeader(stat, filepath)
target, err := os.Readlink(filepath)
if err != nil {
return err
}

hdr.Linkname = target
hdr.Name = destFile
if err := tarWriter.WriteHeader(hdr); err != nil {
return err
}
} else {
//case regular file or other file type like pipe
hdr, err := tar.FileInfoHeader(stat, filepath)
if err != nil {
return err
}
hdr.Name = destFile
err = tarWriter.WriteHeader(hdr)
if err != nil {
log.Println(err)
return err
}

f, err := os.Open(filepath)
if err != nil {
return err
}
defer f.Close()

if _, err := io.Copy(tarWriter, f); err != nil {
return err
}
return f.Close()
}
return nil
}

func (i *Pod) Exec(ctx context.Context, client *kubernetes.Clientset, config *rest.Config, cmd []string) error {

req := client.CoreV1().RESTClient().
Post().
Namespace(i.Namespace).
Resource("pods").
Name(i.Name).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: i.ContainerName,
Command: cmd,
Stdin: true,
Stdout: true,
Stderr: true,
TTY: false,
}, scheme.ParameterCodec)

exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
if err != nil {
return err
}

err = exec.Stream(remotecommand.StreamOptions{
Stdin: strings.NewReader(""),
Stdout: os.Stdout,
Stderr: os.Stderr,
Tty: false,
})

if err != nil {
return err
}
return nil
}

欢迎关注我的其它发布渠道